package com.ponhu.ea2.goodsCenter.provider.facade.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.ponhu.ea2.common.basic.model.ResponseBean;
import com.ponhu.ea2.entity.*;
import com.ponhu.ea2.enums.InventoryTypeEnum;
import com.ponhu.ea2.goodsCenter.provider.mapper.*;
import com.ponhu.ea2.goodsCenter.provider.service.GoodsDataCreateorupdateLogService;
import com.ponhu.ea2.goodsCenter.provider.service.PhInventoryAccessoryService;
import com.ponhu.ea2.goodsCenter.provider.utils.DingTalkHandler;
import com.ponhu.ea2.service.facade.GoodsCenterForWMSService;
import com.ponhu.ea2.wmscenter.facade.bms.PlatformFacade;
import com.ponhu.ea2.wmscenter.model.bms.dto.GoodsCreateOrUpdateDto;
import com.ponhu.ea2.wmscenter.model.bms.dto.inner.GoodsCreateOrUpdateItemDto;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.ObjectUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.dubbo.config.annotation.DubboReference;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.stream.Collectors;

/**
 * @author luyu
 * @create 2021-10-22 16:55
 */
@Slf4j
@Service
public class GoodsCenterForWMSServiceImpl implements GoodsCenterForWMSService {

    @DubboReference(version = "1.0.0", check = false)
    private PlatformFacade platformFacade;

    @Resource
    private PhBrandMapper phBrandMapper;

    @Resource
    private PhCategoryMapper phCategoryMapper;

    @Resource
    private GoodsInventoryMdMapper goodsInventoryMdMapper;

    @Resource
    private GoodsMapper goodsMapper;

    @Resource
    private PhInventoryAccessoryService PhInventoryAccessoryService;

    @Resource
    private GoodsDataCreateorupdateLogService goodsDataCreateorupdateLogService;

    @Resource
    private MaterialMapper materialMapper;

    @Resource
    private PhSeriesMapper phSeriesMapper;

    @Resource
    private PhModelMapper phModelMapper;

    @Resource
    DingTalkHandler dingTalkHandler;

    //
    @Override
    public Boolean createOrUpdateGoodsForWms(Inventory inventory) {
        ResponseBean responseBean = null;
        try {
            // 封装数据
            GoodsCreateOrUpdateItemDto goodsCreateOrUpdateItemDto = assembleData(inventory);
            // 发送请求
            responseBean = sendRequest(goodsCreateOrUpdateItemDto);
        } catch (Exception e) {
            e.printStackTrace();
            log.error("调用wms接口货品编码为:{},出现的异常：", inventory.getInventoryCode(), e);
        } finally {
            // 校验结果
            return checkResult(responseBean, inventory);
        }
    }

    public Boolean checkResult(ResponseBean responseBean, Inventory inventory) {
        if (responseBean == null || responseBean.getCode() != 200) {
            GoodsDataCreateorupdateLog wms = goodsDataCreateorupdateLogService.getLog(
                    inventory.getInventoryCode(), "WMS");
            if (ObjectUtils.isEmpty(wms)) {
                goodsDataCreateorupdateLogService.saveLog(
                        "WMS",
                        "同步wms商品档案失败" + responseBean,
                        inventory.getInventoryCode(),
                        null);
            }
            log.error("货品编码为{}同步wms商品档案失败,错误信息为{}", inventory.getInventoryCode(), responseBean);

            // 对接钉钉保障提醒
            String msg = dingTalkHandler.getDingDingMsgForWms(inventory.getInventoryCode(), responseBean);
            dingTalkHandler.sendMsg(msg, new ArrayList());
            return false;
        }
        return true;
    }

    public GoodsCreateOrUpdateItemDto assembleData(Inventory inventory) {
        GoodsCreateOrUpdateItemDto goodsCreateOrUpdateItemDto = new GoodsCreateOrUpdateItemDto();
        // 根据品牌id和分类id查询数据
        PhBrand phBrand = phBrandMapper.selectById(inventory.getBrandId());
        PhCategory phCategory = phCategoryMapper.selectById(inventory.getCategoryId());
        goodsCreateOrUpdateItemDto.setBrandCode(phBrand.getBrandCode());
        goodsCreateOrUpdateItemDto.setBrandName(phBrand.getCnName());
        goodsCreateOrUpdateItemDto.setCategoryCode(phCategory.getCode());
        goodsCreateOrUpdateItemDto.setCategoryName(phCategory.getName());
        goodsCreateOrUpdateItemDto.setGoodsName(
                StringUtils.isBlank(inventory.getInventoryName())
                        ? inventory.getInventoryCode() : inventory.getInventoryName());
        goodsCreateOrUpdateItemDto.setGwf1(InventoryTypeEnum.getName(inventory.getInventoryType()));
        goodsCreateOrUpdateItemDto.setGwf2(inventory.getIsSecondhand().toString());
        goodsCreateOrUpdateItemDto.setSku(inventory.getInventoryCode());
        goodsCreateOrUpdateItemDto.setUpdateDate(LocalDateTime.now()
                .format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss")));

        goodsCreateOrUpdateItemDto.setUrl(StringUtils.isBlank(inventory.getMainImage())
                ? "" : inventory.getMainImage());
        if (inventory.getMaterialId() != null) {
            StringBuffer size = new StringBuffer();
            // 系列型号
            Material material = materialMapper.selectById(inventory.getMaterialId());
            if (ObjectUtils.isNotEmpty(material)) {
                if (material.getSeriesId() != null) {
                    PhSeries phSeries = phSeriesMapper.selectById(material.getSeriesId());
                    size.append(phSeries.getName());
                }
                if (material.getModelId() != null) {
                    PhModel phModel = phModelMapper.selectById(material.getModelId());
                    goodsCreateOrUpdateItemDto.setColor(phModel.getColourName());// 颜色
                    size.append("|");
                    size.append(phModel.getModel());
                }
                goodsCreateOrUpdateItemDto.setUnit(ObjectUtils.isNotEmpty(material)
                        && StringUtils.isNotBlank(material.getUnit()) ? material.getUnit() : "件");// 单位
                goodsCreateOrUpdateItemDto.setSize(size.toString());
                goodsCreateOrUpdateItemDto.setGwf4(material.getOfficialPrice());//市场参考价
            }
        }
        // 查询商品货品关系表
        GoodsInventoryMd goodsInventoryMd = goodsInventoryMdMapper.selectOne(
                new LambdaQueryWrapper<GoodsInventoryMd>()
                        .eq(GoodsInventoryMd::getInventoryId, inventory.getId()));
        if (ObjectUtils.isNotEmpty(goodsInventoryMd)) {
            Goods goods = goodsMapper.selectById(goodsInventoryMd.getGoodsId());
            // 价格  销售价
            goodsCreateOrUpdateItemDto.setPrice(goods.getSaleTaxPrice());
        }
        // 附件
        String collect = PhInventoryAccessoryService.getInventoryAccessorys(inventory.getId()).stream()
                .map(item -> item.getDictItemLabel()).collect(Collectors.joining(","));
        goodsCreateOrUpdateItemDto.setTsdesc(collect);
        goodsCreateOrUpdateItemDto.setGwf5(inventory.getQualityValue());// 成色值
        goodsCreateOrUpdateItemDto.setGwf6(inventory.getProvenance());// 原产地
        goodsCreateOrUpdateItemDto.setRemark(inventory.getRemarks());// 备注
        return goodsCreateOrUpdateItemDto;
    }

    private ResponseBean sendRequest(GoodsCreateOrUpdateItemDto goodsCreateOrUpdateItemDto) {
        ArrayList<GoodsCreateOrUpdateItemDto> goodsCreateOrUpdateItemDtos = new ArrayList<>();
        goodsCreateOrUpdateItemDtos.add(goodsCreateOrUpdateItemDto);
        GoodsCreateOrUpdateDto goodsCreateOrUpdateDto = new GoodsCreateOrUpdateDto();
        goodsCreateOrUpdateDto.setItems(goodsCreateOrUpdateItemDtos);
        log.info("商品中心推送WMS数据{}", goodsCreateOrUpdateDto.toString());
        ResponseBean responseBean = platformFacade.subGoodsCreateOrUpdate(goodsCreateOrUpdateDto);
        log.info("商品中心推送WMS结果: {},货品编码为：{}", responseBean, goodsCreateOrUpdateItemDto.getSku());
        return responseBean;
    }
}
